<template>
  <lay-card style="height: 100%">
    <lay-layer v-model="visibleTable" :shade="false" :area="['40%', '75%']" :title="relationTitle">
      <Strategy mode="select" @selectRow="selectRow"></Strategy>
    </lay-layer>
    <lay-layer v-model="visible2" :shade="false" :area="['50%', '75%']" title="配置策略">
        <PushParams
            :row-params="rowParams"
            @cancel="closeFilterLayer"
        ></PushParams>
    </lay-layer>
    <lay-container>
      <lay-row space="30" style="margin-top: 15px">
        <lay-col md="4">
          <lay-input v-model="queryForm.address" size="sm" class="queryForm">
            <template #prepend>TCP地址</template>
          </lay-input>
        </lay-col>
        <lay-col md="4">
          <lay-select v-model="queryForm.protocol">
            <template #prepend>网关类型</template>
            <lay-select-option :value="item.value" :label="item.value" v-for="item in protocols"></lay-select-option>
          </lay-select>
        </lay-col>
        <lay-col md="8">
          <lay-select v-model="queryForm.status" size="sm" multiple allow-clear style="width: 100%">
            <template #prepend>任务状态</template>
            <lay-select-option :value="item.value" :label="item.name" v-for="item in taskStatus"></lay-select-option>
          </lay-select>
        </lay-col>
        <lay-col md="4">
          <lay-button type="normal" @click="queryBatFiles">查询</lay-button>
          <lay-button @click="resetFrom">重置</lay-button>
        </lay-col>
      </lay-row>
      <lay-row space="20">
        <lay-col md="24">
          <lay-table
            :page="page"
            :height="'500px'"
            :columns="columns"
            :loading="loading"
            :data-source="dataSource"
            @change="change"
          >
          <template v-slot:toolbar>
            <lay-row space="10">
              <lay-col md="16">
                <h3>TCP客户端列表【服务地址：{{tcpServerAddress}}】</h3>
              </lay-col>
              <lay-col md="6">
                <lay-button size="sm" @click="queryLinkedClients">
                  <template #prefix-icon="{disabled}">layui-icon-refresh-one</template>
                  检查客户端连接状态
                </lay-button>
              </lay-col>
            </lay-row>
          </template>
          <template v-slot:operator="{ row }">
            <lay-button size="xs" @click="relateStrategyButton(row)">关联策略</lay-button>
            <lay-button size="xs" @click="setParams(row)">配置策略</lay-button>
            <lay-button size="xs" type="normal" @click="startJob(row)">启动任务</lay-button>
            <lay-button size="xs" type="danger" @click="stopJob(row)">终止任务</lay-button>
          </template>
        </lay-table>
        </lay-col>
      </lay-row>
    </lay-container>
  </lay-card>
</template>

<script lang="ts">
export default {
  name: "ManageTasks"
}
</script>

<script lang="ts" setup>
import {h, onMounted, reactive, ref} from "vue";
import {
  countClients,
  countRecords,
  getClientList, pushNews,
  queryClientLis,
  queryClients,
  queryStrategyList, relateStrategy, stopTask
} from "../../../api/market/market";
import {notify} from "../../../untils/tip";
import {layer} from "@layui/layui-vue";
import PushParams from "../../../components/Market/PushParams.vue";
import {getConfig} from "../../../api/market/basic";
import {addJobsApi, reloadJobApi} from "../../../api/market/Job";
import Strategy from "./Strategy.vue";

// 初始变量
const loading = ref(false);
const page = reactive({ current: 1, limit: 10, total: 10 });
const protocols: any = ref([]);
const taskStatus = ref([]);
const tcpServerAddress = ref("");


const queryForm = reactive({
    address: null,
    status: ['linked', 'working', 'interrupted', 'finished'],
    protocol: null,
    pageNo: 0,
    pageSize: 10,
});

const actionSubmit = ref([
    {
        text: "确认",
        callback: () => {
            layer.confirm("确认", { shade: false });
        }
    },
    {
        text: "取消",
        callback: () => {
            layer.confirm("取消", { shade: false });
        }
    }
])

const rowParams = ref(null);

const columns = ref([
    { title:"编号", width: "5%", key:"rowId", fixed: "left", sort: "desc" },
    { title:"客户端地址", width: "15%", key:"tcpAddr"},
    { title:"网关类型", width: "5%", key:"protocol"},
    { title:"连接时间", width: "15%", key:"linkTime"},
    { title:"任务状态", width: "5%", key:"linkStatus"},
    { title:"策略ID", width: "5%", key:"filterId"},
    { title:"推送进度", width: "10%", key:"pushProgress"},
    { title:"更新时间", width: "15%", key:"updateTime"},
    { title:"操作", width: "25%", customSlot:"operator", key:"operator", fixed: "right" }
]);
const dataSource = ref([]);

// 关联策略的下拉列表
const strategies = ref([]);
const visible2 = ref(false);
const visibleTable = ref(false);
const currentClient = ref();
const relationTitle = ref("关联策略");


// 页面加载前的运行方法
onMounted(()=>{
  queryLinkedClients();
  queryBatFiles();
  getSelectItems('protocol');
  getSelectItems('system');
  getSelectItems('link_status');
});


// 获取下拉列表选择的值
const getSelectItems = async (target: string) => {
  let {data, code, message} = await getConfig({target: target})
  if(code === 200){
    switch (target) {
      case 'protocol': protocols.value = data; break;
      case 'link_status': taskStatus.value = data; break;
      case 'system':
        let index: any;
        for(index in data){
          let row = data[index]
          console.log('row:', row)
          if(row.name === 'tcpServerAddress'){
            tcpServerAddress.value = row.value;
            console.log('tcpServerAddress:', tcpServerAddress)
          }
        }
        break;
    }
  }else {
    notify('fail', message);
  }
};

const queryLinkedClients = async () => {
  let {data, code, message} = await getClientList({refresh: true});
  if(code === 200 && data !== null){
    await loadDataSource();
    notify('success', "刷新成功！");
  }else {
    notify('fail', "获取客户端失败！");
  }
};

// 设置参数
const setParams = (data: any) => {
  if(data){
    rowParams.value = data.filterRecord;
  }else {
    rowParams.value = null;
  }
  visible2.value = !visible2.value;
};

const closeFilterLayer = () => {
  visible2.value = false;
  loadDataSource();
}

const queryBatFiles = () => {
  page.current = 1;
  queryFilesCount();
  loadDataSource();
}

const change = () => {
  loading.value = true;
  setTimeout(() => {
    loadDataSource();
    loading.value = false;
  }, 1000);
};

const resetFrom = () => {
  queryForm.address = null;
  queryForm.status = ['linked', 'working', 'finished'];
  queryForm.protocol = null;
  queryForm.pageSize = 10;
  queryForm.pageNo = 0;
};

const queryFilesCount = async () => {
  let {data, code, message} = await countClients(queryForm)
  if(code === 200){
    page.total = data;
  }else {
    notify('fail', message);
  }
};

const loadDataSource = async () => {
  dataSource.value = [];
  queryForm.pageNo = (page.current - 1)*page.limit;
  queryForm.pageSize = page.limit;
  let {code, data, message} = await queryClients(queryForm)
  if(code === 200){
    dataSource.value = data;
  }else {
    notify('fail', message);
  }
};

// 关联策略的查询下拉列表
const queryFilterList = async () => {
  let {code, data, message} = await queryStrategyList();
  if(code === 200){
    strategies.value = data;
  }else {
    notify('fail', message);
  }
};

const relateStrategyButton = (data: any) => {
  visibleTable.value = true;
  currentClient.value = data;
  relationTitle.value = "客户端[" + data.tcpAddr + "]关联策略"
}

const selectRow = (id: any) => {
  setRelationStrategy(currentClient.value, id);
}

// 设置关联策略
const setRelationStrategy = async (row: any, target: number) => {
  const params = reactive({rowId: row.rowId, tcpAddr: row.tcpAddr, filterId: target});
  let {code, data, message} = await relateStrategy(params);
  if(code === 200){
    visibleTable.value = false;
    await loadDataSource();
    notify('success', '关联策略成功');
  }else {
    notify('fail', message);
  }
};


// 开始推送任务或者添加定时任务
const startJob = async (params: any) => {
  console.log('params:', params);
  if(params.filterRecord.cornJob){
    // 定时任务入参
    const jobParams = ref({
      taskId: 'TB00' + params.rowId,
      cron: params.filterRecord.cornTime,
      className: "com.hundsun.market.mock.schedule.job.PushMarketNews",
      paramsId: params.rowId,
      status: 1,
      description: params.description
    })
    // 插入 任务信息
    let {code, data, message} = await addJobsApi(jobParams.value);
    if(code === 200){
      notify('success', "插入任务信息成功");
      let result = await reloadJobApi( {taskId: jobParams.value.taskId});
      if(result.code === 200){
        notify('success', "加载任务成功");
      }else {
        notify('fail', result.message);
      }
    }else {
      notify('fail', message);
    }
  }else {
    // 添加 客户端地址 和 推送的网关类型  2023-10-25
    params.filterRecord.rowId = params.rowId;
    params.filterRecord.targetClient = params.tcpAddr;
    params.filterRecord.extField1 = params.protocol;
    // 查询的3个参数不能为null，否则会报错。兼容后端异常        垃圾java---2023-10-13
    if(!params.filterRecord.msgType){params.filterRecord.msgType = ''}
    if(!params.filterRecord.securityId){params.filterRecord.securityId = ''}
    if(!params.filterRecord.mdStreamId){params.filterRecord.mdStreamId = ''}
    // 启动推送任务
    let {code, data, message} = await pushNews(params.filterRecord);
    if(code === 200){
      notify('success', message);
    }else {
      notify('fail', message);
    }
  }

};


const stopJob = async (row: any) => {
    // 启动推送任务
    let {code, data, message} = await stopTask({rowId: row.rowId});
    if(code === 200){
      notify('success', message);
    }else {
      notify('fail', message);
    }
};


</script>

<style scoped>

</style>